package com.bc004346.travelus.AsyncTasks;

import android.app.Activity;
import android.app.Fragment;
import android.os.AsyncTask;
import android.os.Bundle;

import com.bc004346.travelus.DataAccess.TravelUsScreenScraper;
import com.bc004346.travelus.Model.Domain.Flight;

import java.util.Date;
import java.util.List;

import static com.bc004346.travelus.Utility.log;

/**
 * Created by Renats on 3/12/14.
 * Search for flights
 */
public class SearchFlightsTaskFragment extends Fragment {

    private TaskCallbacks mCallbacks;
    private TravelUsScreenScraper mTravelUS;
    private String mOrigin;
    private String mDestination;
    private Date mDepartureDate;
    private Date mReturnDate;
    private Boolean mIsOneWaySearch;

    public SearchFlightsTaskFragment(TravelUsScreenScraper travelUS,
                                     String origin,
                                     String destination,
                                     Date departureDate,
                                     Date returnDate,
                                     Boolean isOneWaySearch) {
        mTravelUS = travelUS;
        mOrigin = origin;
        mDestination = destination;
        mDepartureDate = departureDate;
        mReturnDate = returnDate;
        mIsOneWaySearch = isOneWaySearch;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mCallbacks = (TaskCallbacks) activity;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);
        new SearchTask().execute();
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mCallbacks = null;
    }

    public static interface TaskCallbacks {
        void onSearchPostExecute(List<Flight> flights, Exception e);
    }

    private class SearchTask extends AsyncTask<Void, Void, List<Flight>> {

        private Exception ex = null;

        @Override
        protected void onPostExecute(List<Flight> flights) {
            if (mCallbacks != null) {
                mCallbacks.onSearchPostExecute(flights, ex);
            }
        }

        @Override
        protected List<Flight> doInBackground(Void... params) {
            List<Flight> flights = null;
            try {
                flights = mTravelUS.searchFlights(mOrigin, mDestination, mDepartureDate, mReturnDate, mIsOneWaySearch);
            } catch (Exception e) {
                log(String.format("Exception: %s", e.toString()));
                ex = e;
            }
            return flights;
        }
    }
}
